package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuHasStockVo;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.dao.SpuInfoDescDao;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.feign.CouponFeignService;
import com.atguigu.gulimall.product.feign.SearchFeignService;
import com.atguigu.gulimall.product.feign.WareFeignService;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.swing.*;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private WareFeignService wareFeignService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private BrandService brandService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private SearchFeignService feignService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }
//    @GlobalTransactional
    @Transactional
    @Override
    public void savebyspuvo(SpuSaveVo spuInfoVO) {
        //1保存基本信息 spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();

        BeanUtils.copyProperties(spuInfoVO, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.savebase(spuInfoEntity);
        //2保存spu描述图片spu_info_desc
        List<String> decript = spuInfoVO.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        this.saveSpuInfoDesc(spuInfoDescEntity);
        //3保存spu图片集spu_images
        List<String> images = spuInfoVO.getImages();
        spuImagesService.savaimages(spuInfoEntity.getId(), images);


        //4保存spu的规格参数pms_product_attr_value

        List<BaseAttrs> baseAttrs = spuInfoVO.getBaseAttrs();
        List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(spuInfoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity attrEntity = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(attrEntity.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.savebaseAttrs(productAttrValueEntities);
        //5保存spu的积分信息:跨数据库了 !!gulimall_sms->sms_spu_bounds

        //5保存当前spu对应的sku信息
        //5保存spu的积分信息:跨数据库了 !!gulimall_sms->sms_spu_bounds
        Bounds bounds = spuInfoVO.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r1 = couponFeignService.saveSpuBouds(spuBoundTo);
        if (r1.getCode() != 0) {
            log.error("远程保存spu积分信息失败");
        }
        //5.1)sku的基本信息:pms_sku_info
        List<Skus> skus = spuInfoVO.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(item -> {
                String defaultImg = "";
                for (Images image : item.getImages()) {

                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }

                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImg);//默认图片
                skuInfoService.saveskuinfo(skuInfoEntity);//循环添加数据库

                Long skuId = skuInfoEntity.getSkuId();//保存完就有skuid了

                //5.2)保存sku的图片信息sku_images
                List<SkuImagesEntity> collect = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                   skuImagesEntity.setSkuId(skuId);
                   skuImagesEntity.setImgUrl(img.getImgUrl());
                   skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    BeanUtils.copyProperties(img, skuImagesEntity);
                    return skuImagesEntity;
                }).filter(entity->{
                  //  return true就是需要，flase就是空
                    return !StringUtils.isEmpty(entity.getImgUrl()) ;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect);
                //todo 没有图片路径的无需保存
                //5.3)sku的销售属性信息:sku_sale_attr_value
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    /**
                     *      private Long attrId;
                     *     private String attrName;
                     *     private String attrValue;
                     */
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //5.4)sku的优惠满减等信息！！“跨数据库了 gulimall_sms->sms_sku_ladder\\\sms_sku_full_reduction\\\sms_member_price\\\”
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() >0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0"))==1) {
                    R r = couponFeignService.savaSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {

                        log.error("远程保存sku优惠信息失败");

                    }
                }


            });
        }










    }

    @Override
    public void savebase(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    @Override
    public void saveSpuInfoDesc(SpuInfoDescEntity spuInfoDescEntity) {
        spuInfoDescService.save(spuInfoDescEntity);
    }

    @Override
    public PageUtils queryPagebyparams(Map<String, Object> params) {
        LambdaQueryWrapper<SpuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((w)->{
                w.eq(SpuInfoEntity::getId, key).or().like(SpuInfoEntity::getSpuName, key);
            });

        }
        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {

                    queryWrapper.eq(SpuInfoEntity::getPublishStatus,status);

        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId)&&!"0".equals(brandId)) {

                    queryWrapper.eq(SpuInfoEntity::getBrandId,brandId);

        }
        String catalogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catalogId)&&!"0".equals(catalogId)) {

                queryWrapper.eq(SpuInfoEntity::getCatalogId,catalogId);

        }


        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    //商品上架
    @Override
    public void up(Long spuId) throws IOException {
        // 根据SPU ID查询所有相关的SKU信息
        List<SkuInfoEntity> skuInfoEntityList = skuInfoService.getSksBySpuId(spuId);

        // 提取所有SKU的ID，用于后续查询库存信息
        List<Long> skuidlist = skuInfoEntityList.stream()
                .map(SkuInfoEntity::getSkuId)
                .collect(Collectors.toList());

        // 查询当前SPU下的所有商品属性值
        List<ProductAttrValueEntity> basebyspulist = productAttrValueService.basebyspulist(spuId);

        // 从商品属性值中提取属性ID
        List<Long> attrids = basebyspulist.stream()
                .map(attr -> attr.getAttrId())
                .collect(Collectors.toList());

        // 查询可以作为搜索条件的属性ID列表
        List<Long> selectSearchAttrs = attrService.selectSearchAttrs(attrids);

        // 将搜索属性ID列表转换为Set，以便快速查找
        Set<Long> idset = new HashSet<>(selectSearchAttrs);

        // 过滤出可以作为搜索条件的商品属性值，并转换为SkuEsModel.Attrs对象列表
        List<SkuEsModel.Attrs> attrsList = basebyspulist.stream()
                .filter(item -> idset.contains(item.getAttrId()))
                .map(item -> {
                    SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
                    BeanUtils.copyProperties(item, attrs1);
                    return attrs1;
                })
                .collect(Collectors.toList());

        // 用于存储库存信息的Map，键为SKU ID，值为是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            // 3.1 发送远程调用 库存系统查询是否有库存
            R hasStock = wareFeignService.getSkuHasStock(skuidlist);
            // 构造器受保护 所以写成内部类对象
            stockMap = hasStock.getData(new TypeReference<List<SkuHasStockVo>>(){}).stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
            log.warn("服务调用成功" + hasStock);
        } catch (Exception e) {
            log.error("库存服务调用失败: 原因{}",e);
        }

        // 将SKU信息转换为SkuEsModel对象列表，用于Elasticsearch索引
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> collect = skuInfoEntityList.stream().map(skuInfoEntity -> {
            // 创建SkuEsModel对象并复制SKU信息
            SkuEsModel skuEsModel = new SkuEsModel();
            BeanUtils.copyProperties(skuInfoEntity, skuEsModel);
            skuEsModel.setCategoryId(skuInfoEntity.getCatalogId());
            skuEsModel.setCatalog3Id(skuInfoEntity.getCatalogId());
            // 设置库存信息，如果stockMap为null，则默认为有库存
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(skuInfoEntity.getSkuId()));
            }

            // 设置SKU的价格和默认图片
            skuEsModel.setSkuPrice(skuInfoEntity.getPrice());
            skuEsModel.setSkuImg(skuInfoEntity.getSkuDefaultImg());

            // 查询并设置品牌信息
            BrandEntity brandEntity = brandService.getById(skuEsModel.getBrandId());
            skuEsModel.setBrandName(brandEntity.getName());
            skuEsModel.setBrandImg(brandEntity.getLogo());

            // 查询并设置分类信息
            CategoryEntity categoryEntity = categoryService.getById(skuEsModel.getCategoryId());
            skuEsModel.setCatalogName(categoryEntity.getName());

            // 设置商品属性列表
            skuEsModel.setAttrs(attrsList);

            // 设置热度评分（默认为0）
            skuEsModel.setHotScore(0L);

            // 返回构建好的SkuEsModel对象
            return skuEsModel;
        }).collect(Collectors.toList());
        R r = feignService.productStatusUp(collect);
        if (r.getCode()==0){
            //远程调用成功
            //修改spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.status.SPU_UP.getCode());
            System.out.println("----------------------------------------------------------------------------");
        }
        else {
            //远程调用失败
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(skuId);
        Long spuId = skuInfoEntity.getSpuId();
        SpuInfoEntity spuInfoEntity = getById(spuId);
        return spuInfoEntity;
    }

}